package router

import (
	"github.com/gin-gonic/gin"
)

// Config 路由配置
type Config struct {
	Method      string                // HTTP 方法：GET, POST, PUT, DELETE, PATCH
	Path        string                // 路由路径
	Handler     gin.HandlerFunc       // 处理函数
	NeedAuth    bool                  // 是否需要认证
	Middlewares []gin.HandlerFunc     // 额外的中间件（在认证中间件之后）
}

// Router 路由注册器
type Router struct {
	routes []Config
}

// NewRouter 创建路由注册器
func NewRouter() *Router {
	return &Router{
		routes: make([]Config, 0),
	}
}

// AddRoute 添加路由
func (r *Router) AddRoute(method, path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	r.routes = append(r.routes, Config{
		Method:      method,
		Path:        path,
		Handler:     handler,
		NeedAuth:    needAuth,
		Middlewares: middlewares,
	})
	return r
}

// GET 添加 GET 路由
func (r *Router) GET(path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	return r.AddRoute("GET", path, handler, needAuth, middlewares...)
}

// POST 添加 POST 路由
func (r *Router) POST(path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	return r.AddRoute("POST", path, handler, needAuth, middlewares...)
}

// PUT 添加 PUT 路由
func (r *Router) PUT(path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	return r.AddRoute("PUT", path, handler, needAuth, middlewares...)
}

// DELETE 添加 DELETE 路由
func (r *Router) DELETE(path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	return r.AddRoute("DELETE", path, handler, needAuth, middlewares...)
}

// PATCH 添加 PATCH 路由
func (r *Router) PATCH(path string, handler gin.HandlerFunc, needAuth bool, middlewares ...gin.HandlerFunc) *Router {
	return r.AddRoute("PATCH", path, handler, needAuth, middlewares...)
}

// Register 注册路由到路由组
func (r *Router) Register(group *gin.RouterGroup, authMiddleware gin.HandlerFunc) {
	for _, route := range r.routes {
		handlers := make([]gin.HandlerFunc, 0)
		
		// 如果需要认证，添加认证中间件
		if route.NeedAuth && authMiddleware != nil {
			handlers = append(handlers, authMiddleware)
		}
		
		// 添加额外中间件
		if len(route.Middlewares) > 0 {
			handlers = append(handlers, route.Middlewares...)
		}
		
		// 添加处理函数
		handlers = append(handlers, route.Handler)
		
		// 根据方法注册路由
		switch route.Method {
		case "GET":
			group.GET(route.Path, handlers...)
		case "POST":
			group.POST(route.Path, handlers...)
		case "PUT":
			group.PUT(route.Path, handlers...)
		case "DELETE":
			group.DELETE(route.Path, handlers...)
		case "PATCH":
			group.PATCH(route.Path, handlers...)
		}
	}
}

// RegisterRoutes 批量注册路由（兼容旧接口）
func RegisterRoutes(group *gin.RouterGroup, routes []Config, authMiddleware gin.HandlerFunc) {
	router := NewRouter()
	for _, route := range routes {
		router.routes = append(router.routes, route)
	}
	router.Register(group, authMiddleware)
}

